package base;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

@Deprecated /*测试@Deprecated注解*/
public class GenericDemo {

    public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, InvocationTargetException, NoSuchMethodException {
        GenericDemo demo = new GenericDemo();
        System.out.println(demo.add(1, 2));
        System.out.println(demo.add(1.1, 2.2));

        Object object = demo.getObject(Class.forName("base.User"));
        System.out.println(object);
        User user = (User) object;
        user.setName("A");
        user.setAge(11);
        System.out.println(user);

        test01();
        System.out.println("========");
        test02();
    }

    private static void test01() {
        ArrayList<String> list1 = new ArrayList<String>();
        list1.add("abc");

        ArrayList<Integer> list2 = new ArrayList<Integer>();
        list2.add(123);

        System.out.println(list1.getClass());
        System.out.println(list1.getClass() == list2.getClass());
    }

    private static void test02() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.getClass().getMethod("add", Object.class).invoke(list, "asd");
        // 反射添加add-string方法后，foreach类型转换错误，只能用for循环
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }

    public <T extends Number> double add(T a, T b) {
        return a.doubleValue() + b.doubleValue();
    }

    public <T> T getObject(Class<T> c) throws InstantiationException, IllegalAccessException {
        return c.newInstance();
    }
}
